package com.example.es.myt;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

public class ESTest_Client_Query {
    public static void main(String[] args) throws IOException {
        //创建客户端
        RestHighLevelClient restHighLevelClient=new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
//       //批量查询
//        SearchRequest request=new SearchRequest();
//        request.indices("user");
//        request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
//        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//        SearchHits hit = response.getHits();
//        System.out.println("索引操作"+hit.getTotalHits());
//        for (SearchHit hit1:hit){
//            System.out.println(hit1.getSourceAsString());
//        }
        //分页查询
        SearchRequest request=new SearchRequest();
        request.indices("user");
        SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        query.from(0);
        query.size(2);

        request.source(query);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        SearchHits hit = response.getHits();
        System.out.println("索引操作"+hit.getTotalHits());
        for (SearchHit hit1:hit){
            System.out.println(hit1.getSourceAsString());
        }
        //关闭
        restHighLevelClient.close();
    }
}
